import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws SQLException {
        menu();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的选择");
        int n = sc.nextInt();
        //1.创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java112?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        //2.和数据库服务器建立网络连接
        Connection connection = dataSource.getConnection();

        //3.构造SQL语句
        String sql = null;
        switch(n) {
            case 1:
                sql = insert();
                break;
            case 2:
                sql = delete();
                break;
            case 3:
                sql = select();
                break;
            case 4:
                sql = update();
                break;
        }
        PreparedStatement statement = connection.prepareStatement(sql);

        //4.把SQL发送到服务器上运行
        if(n == 3){
            ResultSet set = statement.executeQuery();
            while(set.next()){
                System.out.print(set.getInt("id"));
                System.out.println(set.getString("name"));
            }
            set.close();
        }else{
            int a = statement.executeUpdate();
            System.out.println(a);
        }

        //5.释放资源
        statement.close();
        connection.close();
    }
    public static void menu(){
        System.out.println("  1. insert ");
        System.out.println("  2. delete ");
        System.out.println("  3. select ");
        System.out.println("  4. update ");
    }
    public static String insert(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入id");
        int id = sc.nextInt();
        System.out.println("请输入name");
        String name = sc.next();
        return "insert into student values("+id+","+"'"+name+"'"+")";
    }
    public static String delete(){
        System.out.println("请输入删除的id");
        Scanner sc = new Scanner(System.in);
        int id = sc.nextInt();
        return "delete from student where id = "+id;
    }
    public static String select(){
        return "select * from student";
    }
    public static String update(){
        System.out.println("请输入修改语句");
        Scanner sc = new Scanner(System.in);
        return sc.nextLine();
    }
}
